//
//  AutoDownloadCheckingOperator.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-4.
//
//

#import "AutoDownloadCheckingOperator.h"
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import "IsolatedStorageFile(CubeLogic).h"
#import "CubeModuleAutoSaveParser.h"
#import "DependsOnParser.h"
#import "IsolatedStorageFile(CubePage).h"
#import "CubeModule.h"
#import <ChamleonSDK/CApplication.h>

@interface AutoDownloadCheckingOperator()


-(NSMutableArray*)loadLocalCheckedList;

-(void)saveLocalCheckedList:(NSArray*)array;

-(BOOL)checkAutoDownloaded;

-(void)checkAutoUpdateed;

@end

@implementation AutoDownloadCheckingOperator

-(id)init{
    self=[super init];
    
    if(self){
        downloadModels=[[NSMutableArray alloc] initWithCapacity:1];
    }
    return self;
}

-(void)start{
    if(![self checkAutoDownloaded]){
        [self checkAutoUpdateed];
    }
}

-(NSArray*)loadLocalCheckedList{
    CubeModuleAutoSaveParser* parser=[[CubeModuleAutoSaveParser alloc] init];
    
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
    
    NSString* username=module.username;

    NSString* file=[IsolatedStorageFile loadAutoSaveFile:username];
    NSData* data=[[NSData alloc] initWithContentsOfFile:file];
    [parser parse:data];
    NSMutableArray* array=[parser getResult];
    return array;
}

-(void)saveLocalCheckedList:(NSArray*)array{
    NSString* str=[CubeModuleAutoSaveParser parserJSONFromArray:array];
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];

    NSString* username=module.username;
    
    NSString* file=[IsolatedStorageFile loadAutoSaveFile:username];
    [str writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
}


-(void)clear{
    [downloadModels removeAllObjects];
}
-(BOOL)checkAutoDownloaded{
    [downloadModels removeAllObjects];
    self.autoDownloadedCount = 0;
    BOOL hasAutoDownloaded = NO;
    
    NSArray* uninstallModules=[DataCenter defaultCenter].uninstallModules;
    if ([uninstallModules count] > 0){

        @autoreleasepool {
            NSMutableArray* autoSaveCubeModules = [self loadLocalCheckedList];
            if (autoSaveCubeModules == nil)
                autoSaveCubeModules = [[NSMutableArray alloc] initWithCapacity:1];
            
            
            for (CubeModel* cubeModel in uninstallModules){
                if (cubeModel.autoDownload){
                    BOOL canDownloaded = YES;
                    for (NSString* autoSaveIdentifier in autoSaveCubeModules){
                        if ([autoSaveIdentifier isEqualToString:cubeModel.identifier]){
                            canDownloaded = NO;
                            break;
                        }
                    }
                    
                    if (canDownloaded){
                        [autoSaveCubeModules addObject:cubeModel.identifier];
                        [downloadModels addObject:cubeModel];
                    }
                }
            }
            [self saveLocalCheckedList:autoSaveCubeModules];
            
        }
        
        self.autoDownloadedCount=[downloadModels count];
        
        if (self.autoDownloadedCount > 0){
            

            hasAutoDownloaded = YES;
            
            NSMutableString* message=[[NSMutableString alloc] initWithCapacity:1];
            [message appendString:@"检测到有以下模块需要下载:\n"];
            
            for (CubeModel* cubeModel in downloadModels){
                [message appendFormat:@"%@\n",cubeModel.name];
            }
            
            if([self.delegate respondsToSelector:@selector(autoSaveDidShowAutoDownloading:message:)])
                [self.delegate autoSaveDidShowAutoDownloading:self message:message];
        }
    }
    return hasAutoDownloaded;
    
}

-(void)checkAutoUpdateed{
    [downloadModels removeAllObjects];
    self.autoDownloadedCount=0;
    NSArray* updatableModules=[DataCenter defaultCenter].updatableModules;
    self.autoDownloadedCount=[updatableModules count];

    if (self.autoDownloadedCount > 0){
        NSMutableString* message=[[NSMutableString alloc] initWithCapacity:1];
        [message appendString:@"检测到有以下模块需要更新:\n"];

        for (CubeModel* cubeModel in updatableModules){
            [message appendFormat:@"%@\n",cubeModel.name];
            
            [downloadModels addObject:cubeModel];

        }
        if([self.delegate respondsToSelector:@selector(autoSaveDidShowUpdating:message:)])
            [self.delegate autoSaveDidShowUpdating:self message:message];

        
    }
}

-(NSArray*)downloadModels{
    return downloadModels;
}

-(NSArray*)dependsList:(NSString*)identifier{
    
    NSString* file = [IsolatedStorageFile dependencieModuleFile:identifier];
    NSData* data=[[NSData alloc] initWithContentsOfFile:file];
    DependsOnParser* parser=[[DependsOnParser alloc] init];
    [parser parse:data];
    NSArray* dependsOnModule=[parser getResult];
    return dependsOnModule;
}


@end
